// scan.js
const util = require("../../utils/util.js")
var app = getApp()
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    cellHeight: '120px',
    openid: wx.getStorageSync('openid'),
    signInfo:null,
    tip_text:'礼品兑换码',
    gridsWidth:'260px',
    gridsHeight:'260px',
    gridsTop:'290px',
    tbTop:'120px',
    topNavH: '65px',
    exchanger: 0,
    signImg: app.globalData.serverUrl +"uploads/wxxcx/sign.png",
    imgH: '500px',
    routers: [
      {
        name: '',
        url: '',
        icon: '',
        code: 'sence_1'
      },
      {
        name: '',
        url: '',
        icon: '',
        code: 'sence_2'
      },
      {
        name: '',
        url: '',
        icon: '',
        code: 'sence_3'
      },
      {
        name: '',
        icon: '',
        code: 'sence_4'
      },
      {
        name: '',
        url: '',
        icon: '',
        code: 'sence_5'
      },
      {
        name: '',
        icon: '',
        code: 'sence_6'
      },
      {
        name: '',
        url: '',
        icon: '',
        code: 'sence_7'
      },
      {
        name: '',
        icon: '',
        code: 'sence_8'
      },
      {
        name: '',
        url: '',
        icon: '',
        code: 'sence_9'
      }
    ]
  },
  onReady: function() {
    
  },
  onLoad: function () {
    console.log('app.globalData.imgurl=>'+app.globalData.serverUrl +"uploads/wxxcx/sign.png")
    var that = this
    
    wx.getSystemInfo({
      success: function (res) {
        var windowHeight = res.windowHeight;
        var windowWidth = res.windowWidth;
        console.log('windowHeight' + windowHeight)
        console.log('windowWidth:'+windowWidth*0.78)
        var radio = windowHeight / 750;
        var statusBarHeight = res.statusBarHeight;
        var windowH = windowHeight - 205 - statusBarHeight;
        var windowW = windowWidth * 0.8;
        var gridsH = windowW;
        var gridsT = 470;
        var tbtop = 120;
        if (windowHeight >= 640&&windowHeight<667){
          gridsH *= 0.85;
          gridsT = 360;
          tbtop = 100;
        } else if (windowHeight >= 667 && windowHeight < 700) {
          gridsH *= 0.9;
          gridsT = 385;
          tbtop = 100;
        } else if (windowHeight < 640) {
          gridsH *= 0.8;
          gridsT = 305;
          tbtop = 80;
        } else if (windowHeight >= 700 && windowHeight < 800) {
          if (windowHeight == 741){
            gridsH *= 1;
            gridsT = 440;
            tbtop = 120;
          }else{
            gridsH *= 0.9;
            gridsT = 470;
            tbtop = 130;
          }
          
        } else if (windowHeight >= 800 && windowHeight <= 812) {
          gridsH *= 1;
          gridsT = 500;
          tbtop = 163;
        } else if (windowHeight > 812) {
          gridsH *= 1;
          gridsT = (windowHeight/736*470);
          tbtop = 163;
        }

        that.setData({
          cellHeight: (windowH) + 'px',
          gridsWidth: (windowW) + 'px',
          gridsHeight: (gridsH) + 'px',
          gridsTop: (gridsT) + 'px',
          tbTop: (tbtop) + 'px',
          picHeight: (windowHeight / 640 * 240) + 'px',
          picWidth: (windowWidth / 360 * 170) + 'px',
          topNavH: (statusBarHeight + 45) + 'px',
          imgH: (windowHeight-50) + 'px',
        })
      }
    })    
  },
  onShow(query) {
    var that = this
    if (wx.getStorageSync('openid')){
      wx.getUserInfo({
        success: (res_info) => {
          wx.request({
            url: app.globalData.apiUrl + 'api/scansence/getInfo', 
            data: {
              openid: wx.getStorageSync('openid')
            },
            header: {
              'content-type': 'application/json',
              "Content-Type": "application/x-www-form-urlencoded" // 默认值
            },
            success(res) { 
              console.log('res.data.qrcode:'+res.data.qrcode) 
              console.log(res.data)
              if(res.data==1){
                that.setData({
                  exchanger: 1
                })
              }else{
                that.setData({
                  signInfo: res.data
                })
              }
                    

            }
          });
        }
      })
    }else{
      //重新获取openid
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          var code = res.code;//发送给服务器的code
          wx.getUserInfo({
            // withCredentials: false,
            success: function (option) {
              app.globalData.userInfo = option.userInfo;
              var userNick = option.userInfo.nickName;//用户昵称
              var avataUrl = option.userInfo.avatarUrl;//用户头像地址
              var gender = option.userInfo.gender;//用户性别
              if (code) {
                wx.request({
                  url: app.globalData.apiUrl + 'api/wechat',
                  //服务器的地址，现在微信小程序只支持https请求，所以调试的时候请勾选不校监安全域名
                  data: {
                    code: code,
                    nickname: userNick,
                    avatar: avataUrl,
                    gender: gender,
                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res_callback) {
                    app.globalData.openid = res_callback.data.openid;
                    // console.log('openid:' + that.globalData.openid);
                    // wx.setStorageSync('name', res_callback.data.nickname);//将获取信息写入本地缓存
                    wx.setStorageSync('openid', res_callback.data.openid);
                    // wx.setStorageSync('imgUrl', res_callback.data.avatar);
                    // wx.setStorageSync('sex', res_callback.data.gender);
                    that.onShow();
                  }
                })

              } else {
                wx.showToast({
                  title: '获取信息失败，请刷新重试',
                  icon: 'success',
                  duration: 2000
                })
              }
            },
            fail: function (option2) {
              console.log('Get Userinfo fail');

            }
          })
        }
      })
    }
    
  }, 
  getScancode: function(e) {
    var that = this;
    if (app.globalData.userInfo==null) {
      wx.navigateTo({
        url: "/pages/loginx/index"
      })
    } else{
       if (app.globalData.openid){
          wx.scanCode({
            onlyFromCamera: false,
            scanType: ['qrCode', 'barCode'],
            success: function (res) {
              // console.log(res.result);
              var url = res.result;
              var result = util.parseURL(url);
              var senceid = 0;
              if(result.senceid){
                senceid = result.senceid;
              }
              wx.request({
                url: app.globalData.apiUrl + 'api/scansence', 
                data: {
                  openid: wx.getStorageSync('openid'),
                  senceid: senceid
                },
                header: {
                  'content-type': 'application/json'
                  // "Content-Type": "application/x-www-form-urlencoded" // 默认值
                },
                success(res2) {
                  // that.onReady()
                  if(res2.data=='no'){
                    wx.showToast({
                      title: '请扫红色二维码',
                      icon: 'fail',
                      duration: 2000
                    })
                  }else if(res2.data=='exchanged'){
                    wx.showToast({
                      title: '无需再打卡',
                      icon: 'success',
                      duration: 2000
                    })
                  }else{
                    wx.showToast({
                      title: '打卡成功',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                  
                  
                  that.onShow()
                  // wx.navigateTo({
                  //   url: "/pages/scancode/index"
                  // });
                }
              });

              

            },
            fail: function (err) {
              // console.log(err);
            },
            complete: function (res) {
              // console.log(res);
            }
          });
          this.setData({
            
          });
      }else{
         if (app.globalData.userInfo) {
           this.setData({
             userInfo: app.globalData.userInfo,
             hasUserInfo: true
           })
         } else if (this.data.canIUse) {
           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
           // 所以此处加入 callback 以防止这种情况
           app.userInfoReadyCallback = res => {
             this.setData({
               userInfo: res.userInfo,
               hasUserInfo: true
             })
           }
         } else {
           // 在没有 open-type=getUserInfo 版本的兼容处理
           wx.getUserInfo({
             success: res => {
               app.globalData.userInfo = res.userInfo
               this.setData({
                 userInfo: res.userInfo,
                 hasUserInfo: true
               })
             }
           })
         }
      }
    }
  },
  getverify: function () {
    wx.scanCode({
      success: function (res1) {
        console.log('thisthisthis')
        console.log(res1.path)
        var path = res1.path.split('?');
        var a = path[1].split('=');
        console.log('a[1]');
        console.log(a[1]);
        var scene = a[1];
        var m_openid = wx.getStorageSync('openid') ? wx.getStorageSync('openid') : app.globalData.openid;
        if (scene) {
          wx.request({
            url: app.globalData.apiUrl + 'api/scansence/exchange',
            data: {
              own_openid: scene,
              manager_openid: m_openid
            },
            header: {
              'content-type': 'application/json',
              "Content-Type": "application/x-www-form-urlencoded" // 默认值
            },
            method: 'POST',
            success(res) {
              var atext = '';
              if (res.data == 2) {
                atext = '只有核销员才能核销';
              } else if (res.data == 3) {
                atext = '未完成扫码';
              } else if (res.data == 4) {
                atext = '不能重复兑换';
              } else if (res.data == 1) {
                atext = '兑换完成';
              }
              wx.showModal({
                title: '提示',
                content: atext,
                success(resconf) {
                  if (resconf.confirm) {
                    wx.switchTab({
                      url: "/pages/index/index"
                    });
                  } else if (resconf.cancel) {
                    wx.switchTab({
                      url: "/pages/index/index"
                    });
                  }
                }
              })

            }
          });
        }
      }
    })
  },
  getUser(e) {
    console.log(e);
    wx.getUserInfo({
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo
        });
      }
    })
  }
})

